<template>
	<div class="app-container" id="doctor/index">
		<el-form ref="form" :model="queryParams" :inline="true" size="small">
			<el-form-item label="医生姓名">
				<el-input v-model="queryParams.doctorName" placeholder="医生姓名" clearable></el-input>
			</el-form-item>
			<el-form-item label="医生职称">
				<el-select v-model="queryParams.title" placeholder="医生职称" clearable>
					<el-option v-for="(item, index) in titleOptions" :key="index" :label="item.dictLabel"
							   :value="item.dictValue"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="审核状态">
				<el-select v-model="queryParams.auditStatus" placeholder="审核状态">
					<el-option label="审核中" value="0"></el-option>
					<el-option label="审核通过" value="1"></el-option>
					<el-option label="审核未通过" value="2"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="手机号">
				<el-input v-model="queryParams.phone" placeholder="手机号" clearable></el-input>
			</el-form-item>
			<el-form-item label="所在医院">
				<el-input v-model="queryParams.hospitalName" placeholder="所在医院" clearable></el-input>
			</el-form-item>
			<el-form-item label="创建时间">
				<el-date-picker v-model="queryParams.createTime" type="month" value-format="yyyy-MM-dd HH:mm:ss" placeholder="创建时间">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit" icon="el-icon-search">查询</el-button>
				<el-button type="default" @click="resetQuery" icon="el-icon-refresh">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
				>新增
				</el-button>
			</el-col>
      <el-col :span="1.5">
        <el-button
          type="cyan"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!--			<el-col :span="1.5">
              <el-popconfirm
                confirm-button-text='当前页'
                cancel-button-text='全部'
                icon="el-icon-info"
                title="请选择导出内容"
                cancel-button-type="default"
                @confirm="handleExport(false)"
                @cancel="handleExport(true)"
              >
                <el-button
                  type="warning"
                  icon="el-icon-download"
                  size="mini"
                  :loading="exporting"
                  slot="reference"
                >导出
                </el-button>
              </el-popconfirm>
            </el-col>-->
			<el-col :span="1.5">
				<el-dropdown size="mini" split-button type="warning" @command="handleExportCommand">
					<i class="el-icon-download"></i> &nbsp;&nbsp;导出
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item command="all">导出全部</el-dropdown-item>
						<el-dropdown-item command="curr">导出当前页</el-dropdown-item>
						<el-dropdown-item command="month">按月份导出</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" size="mini" icon="el-icon-check"
						   @click="passExamine(true)" :disabled="multipleSelection.length == 0">一键通过
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" size="mini" icon="el-icon-close"
						   @click="passExamine(false)" :disabled="multipleSelection.length == 0">一键拒绝
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" size="mini" icon="el-icon-download"
						   @click="downloadQrCode" :disabled="multipleSelection.length == 0">下载二维码
				</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getDoctorList"></right-toolbar>
		</el-row>
		<el-table :data="tableData" stripe style="width: 100%" v-loading="loading"
				  @selection-change="handleSelectionChange">
			<el-table-column type="selection"></el-table-column>
			<el-table-column type="index" :index="indexMethod" align="center" label="序号" width="80"></el-table-column>
			<el-table-column prop="doctorName" align="center" label="医生姓名" width="100"></el-table-column>
			<el-table-column align="center" label="医生职称" width="150">
				<template slot-scope="scope">{{ statusFormat(scope.row.title, titleOptions) }}</template>
			</el-table-column>
			<el-table-column label="所在医院" align="center" :show-overflow-tooltip="true" width="250">
				<template slot-scope="scope">{{ scope.row.hospital.hospitalName }}</template>
			</el-table-column>
			<el-table-column label="所在科室" align="center" :show-overflow-tooltip="true" width="100">
				<template slot-scope="scope">{{ scope.row.dept.deptName }}</template>
			</el-table-column>
			<el-table-column label="注册时间" align="center" :show-overflow-tooltip="true" width="100">
				<template slot-scope="scope">{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</template>
			</el-table-column>
			<el-table-column label="审核状态" align="center" :show-overflow-tooltip="true" width="100">
				<template slot-scope="scope">
					<span v-if="scope.row.auditStatus == 0"><el-tag type="warning">审核中</el-tag></span>
					<span v-if="scope.row.auditStatus == 1"><el-tag type="success">审核通过</el-tag></span>
					<span v-if="scope.row.auditStatus == 2"><el-tag type="danger">未通过</el-tag></span>
				</template>
			</el-table-column>
			<el-table-column label="阳光工程" align="center" width="100">
				<template slot-scope="scope">
					<el-switch :value="scope.row.sunshine" active-color="#ffc833" :active-value="1" :inactive-value="0"
							   :disabled="scope.row.sunshine==1" @change="handleSunshineChange(scope.row)"></el-switch>
				</template>
			</el-table-column>
<!--			<el-table-column label="是否审核" align="center" width="100">
				<template slot-scope="scope">
					<span v-if="scope.row.auditStatus == 0">
						<el-switch :value="scope.row.auditStatus" active-color="#67C23A" :active-value="1"
								   :inactive-value="0" @change="handleAuditChange(scope.row)"></el-switch>
					</span>
					<span v-if="scope.row.auditStatus == 1">
						<el-switch :value="scope.row.auditStatus" active-color="#67C23A" :active-value="1"
								   :inactive-value="2" @change="handleAuditChange(scope.row)"></el-switch>
					</span>
					<span v-if="scope.row.auditStatus == 2">
						<el-switch :value="scope.row.auditStatus" active-color="#67C23A" :active-value="1"
								   :inactive-value="2" @change="handleAuditChange(scope.row)"></el-switch>
					</span>
				</template>
			</el-table-column>
			<el-table-column label="设为专家" align="center" width="100">
				<template slot-scope="scope">
					<el-switch :value="scope.row.isExpert" :active-value="1" :inactive-value="0"
							   @change="handleSwitchChange(scope.row)"></el-switch>
				</template>
			</el-table-column>-->
			<el-table-column prop="goodSkill" label="擅长领域" align="center" :show-overflow-tooltip="true"
							 width="200"></el-table-column>
			<el-table-column prop="briefIntroduction" label="医生简介" align="center" :show-overflow-tooltip="true"
							 width="200"></el-table-column>
			<el-table-column prop="briefExperience" label="职业经历" align="center" :show-overflow-tooltip="true"
							 width="200"></el-table-column>
			<el-table-column fixed="right" label="操作" align="center" width="320">
				<template slot-scope="scope">
					<el-button type="text" @click="view(scope.row.doctorId)" icon="el-icon-link" style="margin-right: 10px;">查看</el-button>
					<span @click.stop style="margin-right: 5px;">
						<el-dropdown>
							<span class="el-dropdown-link">
								<el-button type="text" icon="el-icon-key">权限<i class="el-icon-arrow-down el-icon--right"></i></el-button>
							</span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item>
									<span @click.stop>
										<el-switch active-text="阳光工程" :value="scope.row.sunshine" active-color="#ffc833" :active-value="1" :inactive-value="0"
											:disabled="scope.row.sunshine==1" @change="handleSunshineChange(scope.row)"></el-switch>
									</span>
								</el-dropdown-item>
								<el-dropdown-item>
									<span @click.stop v-if="scope.row.auditStatus == 0">
										<el-switch active-text="是否审核" :value="scope.row.auditStatus" active-color="#67C23A" :active-value="1"
											:inactive-value="0" @change="handleAuditChange(scope.row)"></el-switch>
									</span>
									<span @click.stop v-if="scope.row.auditStatus == 1">
										<el-switch active-text="是否审核" :value="scope.row.auditStatus" active-color="#67C23A" :active-value="1"
											:inactive-value="2" @change="handleAuditChange(scope.row)"></el-switch>
									</span>
									<span @click.stop v-if="scope.row.auditStatus == 2">
										<el-switch active-text="是否审核" :value="scope.row.auditStatus" active-color="#67C23A" :active-value="1"
											:inactive-value="2" @change="handleAuditChange(scope.row)"></el-switch>
									</span>
								</el-dropdown-item>
								<el-dropdown-item>
									<span @click.stop>
										<el-switch active-text="设为专家" :value="scope.row.isExpert" :active-value="1" :inactive-value="0"
											@change="handleSwitchChange(scope.row)"></el-switch>
									</span>
								</el-dropdown-item>
								<el-dropdown-item>
									<span @click.stop>
										<el-switch active-text="视频医生" :value="scope.row.isVideo" :active-value="1" :inactive-value="0"
											@change="handleVideoChange(scope.row)" active-color="#F56C6C"></el-switch>
									</span>
								</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</span>
					<el-dropdown>
					  	<span class="el-dropdown-link">
					    	<span>
								<el-button type="text" icon="el-icon-chat-round">短信<i class="el-icon-arrow-down el-icon--right"></i></el-button>
							</span>
					  	</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item v-if="scope.row.isExpert === 1" icon="el-icon-chat-line-round" @click.native="previewMessage(scope.row, 'SMS_461815130')">任务发起（专家）</el-dropdown-item>
							<el-dropdown-item v-if="scope.row.isExpert === 0" icon="el-icon-chat-line-round" @click.native="previewMessage(scope.row, 'SMS_461860560')">任务发起（非专家）</el-dropdown-item>
							<el-dropdown-item icon="el-icon-chat-square" @click.native="previewMessage(scope.row, 'SMS_461885162')">积分变更</el-dropdown-item>
							<el-dropdown-item icon="el-icon-chat-dot-round" @click.native="previewMessage(scope.row, 'SMS_461830148')">任务完成</el-dropdown-item>
							<el-dropdown-item icon="el-icon-chat-dot-square" @click.native="previewMessage(scope.row, 'SMS_461890147')">任务未完成</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
          <el-button type="text" @click="reSendContract(scope.row)" icon="el-icon-tickets" style="margin-right: 10px;">补发合同</el-button>
          <el-upload
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="(response, file, fileList) => handleBusCertificateSuccess(response, file, fileList, scope.row)"
            :before-upload="beforeUpload">
            <el-button type="text">上传照片</el-button>
          </el-upload>
				</template>
			</el-table-column>
		</el-table>
		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
					:page-sizes="[10, 20, 50, 100]" @pagination="getDoctorList"/>
		<bind-patient-table v-if="flag" :doctorId="doctorId" @close="close"></bind-patient-table>
		<subscribe-dialog v-if="dialogFlag" :currentUserId="currentUserId" :type="type"
						  @close="subscribeClose"></subscribe-dialog>
		<div v-for="item in multipleSelection" :key="item.doctorId">
			<vue-qr :qid="item.doctorId.toString()" v-show="false"
					:text="'https://console.jsycgm.com?bindId=' + item.doctorId" :size="300"
					:callback="qrCallback"></vue-qr>
		</div>

		<!-- 添加或修改医生对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="600" append-to-body>
			<el-form ref="form" :model="form" size="large" :rules="rules" label-width="100px">
				<el-form-item label="医生姓名" prop="doctorName">
					<el-input v-model="form.doctorName" placeholder="请输入医生姓名"/>
				</el-form-item>
				<el-form-item label="手机号码" prop="phone">
					<el-input v-model="form.phone" maxlength="11" :disabled="form.doctorId !== null" placeholder="请输入手机号码"/>
				</el-form-item>
				<el-form-item label="医生职称" prop="title">
					<el-select v-model="form.title" placeholder="请选择医生职称" style="width: 100%;">
						<el-option
							v-for="item in titleOptions"
							:key="item.dictId"
							:label="item.dictLabel"
							:value="item.dictValue">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属医院" prop="hospitalName">
					<el-autocomplete v-model="form.hospitalName" clearable @clear="handleClearHospital"
									 :fetch-suggestions="getHospital" @select="handleHospitalSelect"
									 value-key="hospitalName" placeholder="请选择所属医院" style="width: 100%;">
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="所属部门" prop="deptName">
					<el-autocomplete v-model="form.deptName" clearable @clear="handleClearDept"
									 :fetch-suggestions="getDept" @select="handleDeptSelect"
									 value-key="deptName" placeholder="请选择所属部门" style="width: 100%;">
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="身份证号" prop="idCard">
					<el-input v-model="form.idCard" placeholder="请输入身份证号"/>
				</el-form-item>
				<el-form-item label="出生日期" prop="birthday">
					<el-date-picker clearable size="large" style="width: 100%;"
									v-model="form.birthday"
									type="date"
									value-format="yyyy-MM-dd"
									placeholder="选择出生日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="工牌照" prop="badge">
					<el-upload
						:action="upload.url"
						:headers="upload.headers"
						:show-file-list="false"
						:on-success="handleBadgeSuccess"
						:before-upload="beforeUpload">
						<img style="width: 100px; height: 100px" v-if="form.badge"
							 :src="ossUrl + form.badge" alt=""/>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="执业证书" prop="certificate">
					<el-upload
						:action="upload.url"
						:headers="upload.headers"
						:show-file-list="false"
						:on-success="handleCertificateSuccess"
						:before-upload="beforeUpload">
						<img style="width: 100px; height: 100px" v-if="form.certificate"
							 :src="ossUrl + form.certificate" alt=""/>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="证件照" prop="credentials">
					<el-upload
						:action="upload.url"
						:headers="upload.headers"
						:show-file-list="false"
						:on-success="handleCredentialsSuccess"
						:before-upload="beforeUpload">
						<img style="width: 100px; height: 100px" v-if="form.credentials"
							 :src="ossUrl + form.credentials" alt=""/>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="擅长领域" prop="goodSkill">
					<el-input v-model="form.goodSkill" style="width: 80%;" rows="3" type="textarea"
							  placeholder="请输入内容"/>
				</el-form-item>
				<el-form-item label="医生简介" prop="briefIntroduction">
					<el-input v-model="form.briefIntroduction" style="width: 80%;" rows="3" type="textarea"
							  placeholder="请输入内容"/>
				</el-form-item>
				<el-form-item label="职业经历" prop="briefExperience">
					<el-input v-model="form.briefExperience" style="width: 80%;" rows="3" type="textarea"
							  placeholder="请输入内容"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 模板上传 -->
		<el-dialog title="模板上传" :visible.sync="uploadVisible" width="400px" append-to-body>
			<el-upload ref="upload" :limit="1" accept=".pdf" :headers="upload.headers" :action="upload.url"
					   :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
					   :on-success="handleFileSuccess" :auto-upload="false" drag>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">
					将文件拖到此处，或
					<em>点击上传</em>
				</div>
				<div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“dpf”格式文件！</div>
			</el-upload>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" size="small" @click="uploadTemplate">确 定</el-button>
				<el-button size="small" @click="uploadVisible = false">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 任务添加 -->
		<template>
			<div>
				<el-dialog v-bind="$attrs" :visible.sync="doctorTask" title="任务定制">
					<el-row :gutter="15">
						<el-form ref="elForm" :model="formData" :rules="rulesList" size="medium" label-width="100px"
								 label-position="left">
							<el-col :span="24">
								<el-form-item label="任务" prop="field102">
									<el-input v-model="formData.field102" placeholder="请输入任务积分上限" clearable
											  :style="{width: '100%'}">
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item label="日期选择" prop="field104">
									<el-date-picker type="month" v-model="formData.field104" format="yyyy-MM"
													value-format="yyyy-MM"
													:style="{width: '100%'}" placeholder="请选择日期选择"
													clearable></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="自动顺延" prop="field105" required>
									<el-switch v-model="formData.field105"></el-switch>
								</el-form-item>
							</el-col>
						</el-form>
					</el-row>
					<div slot="footer">
						<el-button @click="doctorTask = false">取消</el-button>
						<el-button type="primary" @click="handleConfirm">确定</el-button>
					</div>
				</el-dialog>
			</div>
		</template>
		<message-preview v-if="message.visible" :visible.sync="message.visible" :doctor.sync="message.doctor" :msg-code.sync="message.msgCode"></message-preview>
		<export-month-dialog v-if="exportMonth.visible" :visible.sync="exportMonth.visible" bus-type="doctor"></export-month-dialog>
	</div>
</template>

<script>
import VueQr from 'vue-qr'
import {GetDoctorList, EditDoctor, delDoctor, exportDoctor, updateAuditStatusByIds, GetDoctorById, addDoctorTask, addDoctor} from '@/api/doctor'
import {generateContract, uploadTemplate} from '@/api/sunshine'
import BindPatientTable from '@/views/doctor/component/bind-patient-table'
import SubscribeDialog from '@/views/doctor/component/subscribe-dialog'
import MessagePreview from '@/views/doctor/component/message-preview'
import ExportMonthDialog from '@/views/components/export-month-dialog'
import {getToken} from "@/utils/auth";
import {listHospital} from "@/api/hospital/hospital";
import {listDept} from '@/api/hospital/dept'

export default {
	name: "Doctor/index",
	components: {BindPatientTable, SubscribeDialog, VueQr, MessagePreview, ExportMonthDialog},
	data() {
		return {
			tableData: [],
			total: 0,
			single: true,
      // 非多个禁用
      multiple: true,
			loading: false,
			queryParams: {
				doctorName: undefined,
				title: undefined,
				auditStatus: undefined,
				hospitalName: undefined,
				phone: undefined,
				createTime: undefined,
				pageNum: 1,
				pageSize: 10,
				orderByColumn: 'create_time',
				isAsc: 'desc'
			},
			doctorTask: false,
			formData: {
				field102: undefined,
				field104: null,
				mobile: 1,
				field105: true,
			},
			rulesList: {
				field104: [{
					required: true,
					message: '请选择日期选择',
					trigger: 'change'
				}],
				field102: [{
					required: true,
					message: '请输入任务积分上限',
					trigger: 'blur'
				}, {
					pattern: /^[0-9]*$/,
					message: '请输入数字',
					trigger: 'blur'
				}],
			},
			field102Options: [],
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				doctorName: [
					{required: true, message: "医生姓名不能为空", trigger: "blur"}
				],
				phone: [
					{ required: true, message: "手机号码不能为空", trigger: "blur" },
					{
						pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
						message: "请输入正确的手机号码",
						trigger: "blur",
					}
				],
				hospitalName: [
					{required: true, message: "所属医院不能为空", trigger: "change"}
				],
				deptName: [
					{required: true, message: "所属部门不能为空", trigger: "change"}
				],
				title: [
					{required: true, message: "医生职称不能为空", trigger: "change"}
				],
				goodSkill: [
					{required: true, message: "擅长领域不能为空", trigger: "blur"}
				],
				briefIntroduction: [
					{required: true, message: "医生简介不能为空", trigger: "blur"}
				]
			},
			open: false,
			title: '修改医生',
			flag: false,
			dialogFlag: false,
			doctorId: undefined,
			currentUserId: undefined,
			type: 'doctor',
			showSearch: true,
			exporting: false,
			titleOptions: [],
			taskOptions: [],
			multipleSelection: [],
			baseUrl: this.$baseUrl,
			ossUrl: this.$ossUrl,
			upload: {
				// 是否禁用上传
				isUploading: false,
				// 设置上传的请求头部
				headers: {Authorization: "Bearer " + getToken()},
				// 上传的地址
				url: process.env.VUE_APP_BASE_API + "/uploadOssFile",
			},
			uploadVisible: false,
			templateId: undefined,
			currentRow: undefined,
			selectLoading: false,
			message: {
				visible: false,
				doctor: {},
				msgCode: ''
			},
			exportMonth: {
				visible: false
			}
		};
	},
	created() {
		this.getDicts('doctor_title').then(response => {
			this.titleOptions = response.data;
		})
	},
	mounted() {
		this.getDoctorList();
	},
	methods: {
		getDoctorList() {
			this.loading = true;
			GetDoctorList(this.queryParams).then(res => {
				this.tableData = res.rows;
				this.total = res.total;
				this.loading = false;
			})
		},
		handleClick(doctorId) {
			this.doctorId = doctorId;
			this.flag = true;
		},
		onSubmit() {
			this.getDoctorList()
		},
		resetQuery() {
			this.queryParams.doctorName = undefined;
			this.queryParams.title = undefined;
			this.queryParams.createTime = undefined;
		},
		close() {
			this.flag = false;
		},
		subscribeClose() {
			this.dialogFlag = false;
		},
		sendSubscribe(userId) {
			this.dialogFlag = true;
			this.currentUserId = userId;
		},
		view(doctorId) {
			this.$router.push({path: '/doctor/view', query: {doctorId: doctorId}})
		},
		task(doctorId) {
			this.doctorId = doctorId
			this.doctorTask = true
		},
		handleConfirm() {
			console.log(this.formData)
			var options = []
			for (var i = 0; i < this.field102Options.length; i++) {
				if (this.field102Options[i].dictValue == this.formData.field102) {
					options = this.field102Options[i]
				}
			}
			let param = {
				doctorId: this.doctorId,
				totalPoints: this.formData.field102,
				year: parseInt(this.formData.field104.substring(0, 4)),
				month: parseInt(this.formData.field104.substring(5, 7)),
				isPostpone: this.formData.field105 + ""
			}
			addDoctorTask(param).then(res => {
				if (res.code == 200) {
					this.msgSuccess("医生任务定制成功");
					this.doctorTask = false
				}
			})
		},
		onClose() {
			this.$refs['elForm'].resetFields()
		},
		/*close() {
			this.$emit('update:visible', false)
		},*/
		handleSelectionChange(val) {
			this.ids = val.map(item => item.doctorId)
			this.single = val.length != 1;
      this.multiple = !val.length
			this.multipleSelection = val;
		},
		passExamine(flag) {
			let ids = [];
			let auditStatus = flag ? 1 : 2;
			for (let i = 0; i < this.multipleSelection.length; i++) {
				ids.push(this.multipleSelection[i].doctorId);
			}
			updateAuditStatusByIds({auditStatus: auditStatus, ids: ids.join(",")}).then(res => {
				if (res.code == 200) {
					this.msgSuccess(res.msg);
					this.getDoctorList();
				}
			})
		},
		downloadQrCode() {
			for (let i = 0; i < this.multipleSelection.length; i++) {
				this.downloadPicture(this.multipleSelection[i].qrCodeUrl, this.multipleSelection[i].doctorName)
			}
		},
		downloadPicture(imgSrc, name) {
			const image = new Image();
			// 解决跨域 Canvas 污染问题
			image.setAttribute("crossOrigin", "anonymous");
			image.src = imgSrc;
			image.onload = () => {
				const canvas = document.createElement("canvas");
				canvas.width = image.width;
				canvas.height = image.height;
				const context = canvas.getContext("2d");
				context.drawImage(image, 0, 0, image.width, image.height);
				canvas.toBlob((blob) => {
					const url = URL.createObjectURL(blob);
					const a = document.createElement("a");
					a.download = name || "photo";
					a.href = url;
					a.click();
					a.remove();
					URL.revokeObjectURL(url);
				});
			};
		},
		qrCallback(qrCodeUrl, id) {
			let doctor = this.multipleSelection.find((item) => {
				return item.doctorId == id
			});
			doctor.qrCodeUrl = qrCodeUrl;
		},
		handleSwitchChange(row) {
			let text = row.isExpert == 1 ? `您确定要取消【${row.doctorName}】医生的专家资格吗?` : `您确定要将【${row.doctorName}】医生设为专家吗?`;
			let isExpert = row.isExpert == 1 ? 0 : 1;
			this.$confirm(text, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				EditDoctor({doctorId: row.doctorId, isExpert: isExpert}).then(res => {
					this.msgSuccess("您的操作已提交成功");
					this.getDoctorList();
				})
			})
		},
		handleVideoChange(row) {
			let text = row.isVideo == 1 ? `您确定要取消【${row.doctorName}】医生的视频资格吗?` : `您确定要将【${row.doctorName}】医生设为视频医生吗?`;
			let isVideo = row.isVideo == 1 ? 0 : 1;
			this.$confirm(text, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				EditDoctor({doctorId: row.doctorId, isVideo: isVideo}).then(res => {
					this.msgSuccess("您的操作已提交成功");
					this.getDoctorList();
				})
			})
		},
		handleAuditChange(row) {
			let text = row.auditStatus == 1 ? `您确定要取消【${row.doctorName}】医生的审核状态吗?` : `您确定要通过【${row.doctorName}】医生的审核状态吗?`;
			let auditStatus = row.auditStatus == 1 ? 2 : 1;
			this.$confirm(text, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				EditDoctor({doctorId: row.doctorId, auditStatus: auditStatus}).then(res => {
					if (res.code == 200) {
						this.msgSuccess("您的操作已提交成功");
						this.getDoctorList();
					}
				})
			})
		},
    reSendContract(row) {
      this.$confirm(`该操作会向【${row.doctorName}】医生发送签约合同，是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.setSunshineForDoctor(row, 'YCPT2024S');
      })
    },
		handleSunshineChange(row) {
			this.currentRow = row;
			this.$confirm(`该操作会向【${row.doctorName}】医生发送签约合同，是否继续？`, '提示', {
				distinguishCancelAndClose: true,
				confirmButtonText: '发送默认模板',
				cancelButtonText: '不发送合同，直接设为阳光工程',
				// cancelButtonText: '上传新模板',
				type: 'warning'
			}).then(() => {
				this.setSunshineForDoctor(this.currentRow, 'YCPT2024S')
			}).catch(action => {
				console.log(action)
				if (action === 'cancel') {
					// this.uploadVisible = true;
					EditDoctor({doctorId: row.doctorId, sunshine: 1}).then(res => {
						if (res.code == 200) {
							this.msgSuccess("您的操作已提交成功");
							this.getDoctorList();
						}
					})
				}
			});
		},
		setSunshineForDoctor(row, templateId) {
			EditDoctor({doctorId: row.doctorId, sunshine: 1}).then(res => {
				if (res.code == 200) {
					generateContract({
						doctorId: row.doctorId, doctorName: row.doctorName,
						customerId: row.sysUser.customerId, templateId: templateId
					}).then(response => {
						if (response.code == 200) {
							this.msgSuccess("您的操作已提交成功");
							this.getDoctorList();
						}
					})
				}
			})
		},
		indexMethod(index) {
			return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
		},
		/** 导出按钮操作 */
		handleExport(flag) {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有医生数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				this.exporting = true;
				this.msgInfo('当前医生数量较多，可能导出耗时较长，请您耐心等待...');
				if (flag) {
					return exportDoctor();
				} else {
					return exportDoctor(queryParams);
				}
			}).then(response => {
				this.download(response.msg);
				this.exporting = false;
			}).catch(function () {
			});
		},
		handleExportCommand(command) {
			console.log(command)
			if (command === 'all') {
				this.handleExport(true);
			} else if (command === 'curr') {
				this.handleExport(false);
			} else if (command === 'month') {
				this.exportMonth.visible = true;
			}
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加医生";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const doctorId = row.doctorId || this.ids
			GetDoctorById(doctorId).then(response => {
				this.form = response.data;
				this.open = true;
				this.title = "修改医生";
			});
		},
    /** 删除按钮操作 */
    handleDelete(row) {
      const doctorIds = row.doctorId || this.ids;
      this.$confirm('是否确认删除参数编号为"' + doctorIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delDoctor(doctorIds).then(res => {
          if (res.code === 200) {
            this.getDoctorList();
            this.msgSuccess("删除成功");
          }
        })
      }).catch(function() {});
    },
		// 表单重置
		reset() {
			this.form = {
				doctorId: null,
				userId: null,
				hospitalId: null,
				deptId: null,
				doctorName: null,
				hospitalName: null,
				deptName: null,
				title: null,
				idCard: null,
				birthday: null,
				point: null,
				pointUpperLimit: null,
				sunshine: null,
				auditStatus: 0,
				isExpert: null,
				idCardFront: null,
				idCardBack: null,
				badge: null,
				certificate: null,
				credentials: null,
				headUrl: null,
				qrCodeUrl: null,
				goodSkill: null,
				briefIntroduction: null,
				briefExperience: null,
				doctorClinicTimeRemark: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null
			};
			this.resetForm("form");
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.doctorId != null) {
						EditDoctor(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("修改成功");
								this.open = false;
								this.getDoctorList()
							}
						});
					} else {
						addDoctor(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("新增成功");
								this.open = false;
								this.getDoctorList();
							}
						});
					}
				}
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		statusFormat(value, options) {
			return this.selectDictLabel(options, value);
		},
		beforeUpload(file) {
			let fileType = file.type;
			if (fileType === 'image/jpeg' || fileType === 'image/png') {
				return true;
			} else {
				this.$message.error('请插入图片类型文件(jpg/jpeg/png)');
				return false;
			}
		},
		handleBadgeSuccess(res) {
			this.form.badge = res.fileName;
		},
		handleCertificateSuccess(res) {
			this.form.certificate = res.fileName;
		},
		handleCredentialsSuccess(res) {
			this.form.credentials = res.fileName;
		},
    handleBusCertificateSuccess(response, file, fileList, row) {
      EditDoctor({doctorId: row.doctorId, certificate: response.fileName}).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
        }
      })
    },
		// 文件上传中处理
		handleFileUploadProgress(event, file, fileList) {
			this.upload.isUploading = true;
		},
		// 文件上传成功处理
		handleFileSuccess(response, file, fileList) {
			this.uploadVisible = false;
			this.upload.isUploading = false;
			this.$refs.upload.clearFiles();
			uploadTemplate({docUrl: response.url}).then(res => {
				this.setSunshineForDoctor(this.currentRow, res.msg)
			})
		},
		uploadTemplate(docUrl) {
			this.$refs.upload.submit();
		},
		getHospital(hospitalName, cb) {
			let params = {
				pageNum: 1,
				pageSize: 50,
				hospitalName: hospitalName
			};
			listHospital(params).then(res => {
				cb(res.rows)
			})
		},
		handleHospitalSelect(item) {
			this.form.hospitalId = item.hospitalId;
			console.log(this.form.hospitalId)
			console.log(this.form.hospitalName)
		},
		handleClearHospital() {
			document.activeElement.blur();
			this.form.hospitalId = null;
			this.form.hospitalName = null;
		},
		getDept(deptName, cb) {
			listDept({parentId: 1, deptName: deptName}).then(response => {
				cb(response.data)
			})
		},
		handleDeptSelect(item) {
			this.form.deptId = item.deptId;
		},
		handleClearDept() {
			document.activeElement.blur();
			this.form.deptId = null;
			this.form.deptName = null;
		},
		previewMessage(row, msgCode) {
			this.message.visible = true;
			this.message.doctor = row;
			this.message.msgCode = msgCode;
		},
    uploadPic() {
    
    }
	}
}
</script>

<style lang="scss" scoped>
.image {
	width: 100px;
	height: 50px;
}

.el-dropdown-link {
	cursor: pointer;
	color: #409EFF;
}

.el-icon-arrow-down {
	font-size: 12px;
}
</style>
